<template>
  <div class="notifications-page">
    <div class="page-header">
      <h2>通知中心</h2>
      <div class="header-actions">
        <el-button type="primary" @click="markAllAsRead"
          :disabled="loading || notifications.length === 0 || !hasUnread">
          清空所有通知
        </el-button>
      </div>
    </div>

    <el-card class="notification-container">
      <div class="notification-filter">
        <el-radio-group v-model="filterType" size="large">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="unread">未读</el-radio-button>
          <el-radio-button label="read">已读</el-radio-button>
        </el-radio-group>
      </div>

      <el-table v-loading="loading" :data="filteredNotifications" style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无通知'" row-key="id" @row-click="handleRowClick">
        <el-table-column width="50">
          <template #default="scope">
            <el-icon v-if="!scope.row.read" color="#409EFF">
              <CirclePlus />
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getNotificationType(scope.row.type)" size="small">
              {{ getNotificationTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="标题" prop="title" />

        <el-table-column label="内容" prop="content" show-overflow-tooltip />

        <el-table-column label="时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button v-if="!scope.row.read" type="primary" size="small" text @click.stop="markAsRead(scope.row)">
              标记已读
            </el-button>
            <span v-else class="read-status">已读</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" @update:current-page="currentPage = $event"
          @update:page-size="pageSize = $event" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CirclePlus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const notifications = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const filterType = ref('all')

// 计算属性：根据过滤条件筛选通知
const filteredNotifications = computed(() => {
  if (filterType.value === 'all') {
    return notifications.value
  } else if (filterType.value === 'unread') {
    return notifications.value.filter(n => !n.read)
  } else {
    return notifications.value.filter(n => n.read)
  }
})

// 计算属性：是否有未读通知
const hasUnread = computed(() => {
  return notifications.value.some(n => !n.read)
})

// 加载通知列表
const loadNotifications = async () => {
  loading.value = true
  try {
    const res = await request.get('/notifications', {
      params: {
        page: currentPage.value - 1, // 后端页码从0开始
        size: pageSize.value
      }
    })

    if (res.code === 200 && res.data) {
      notifications.value = res.data.content || []
      total.value = res.data.totalElements || 0
    }
  } catch (error) {
    console.error('加载通知失败:', error)
    ElMessage.error('加载通知失败')
  } finally {
    loading.value = false
  }
}

// 标记单个通知为已读
const markAsRead = async (notification) => {
  if (notification.read) return

  try {
    const res = await request.put(`/notifications/${notification.id}/read`)
    if (res.code === 200) {
      notification.read = true
      ElMessage.success('已标记为已读')
    }
  } catch (error) {
    console.error('标记通知已读失败:', error)
    ElMessage.error('标记通知已读失败')
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  if (!hasUnread.value || loading.value) return

  try {
    ElMessageBox.confirm('确定要清空所有通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      loading.value = true
      const res = await request.put('/notifications/read-all')
      if (res.code === 200) {
        // 清空通知列表，因为后端已经删除了所有通知
        notifications.value = []
        total.value = 0
        ElMessage.success('已清空所有通知')
      } else {
        ElMessage.error('清空通知失败')
      }
      loading.value = false
    }).catch(() => {
      // 用户取消操作
    })
  } catch (error) {
    console.error('清空通知失败:', error)
    ElMessage.error('清空通知失败')
    loading.value = false
  }
}

// 处理页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadNotifications()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadNotifications()
}

// 处理行点击
const handleRowClick = (row) => {
  if (!row.read) {
    markAsRead(row)
  }
}

// 获取通知类型样式
const getNotificationType = (type) => {
  const types = {
    'overdue': 'warning',
    'return': 'success',
    'borrow': 'info',
    'fine': 'danger'
  }
  return types[type] || 'info'
}

// 获取通知类型名称
const getNotificationTypeName = (type) => {
  const names = {
    'overdue': '逾期提醒',
    'return': '归还提醒',
    'borrow': '借阅提醒',
    'fine': '罚款提醒'
  }
  return names[type] || '系统通知'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''

  const date = new Date(time)
  const now = new Date()

  // 如果是今天
  if (date.toDateString() === now.toDateString()) {
    return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  // 如果是昨天
  const yesterday = new Date(now)
  yesterday.setDate(now.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  // 其他日期
  return date.toLocaleDateString('zh-CN') + ' ' +
    date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 生命周期钩子
onMounted(() => {
  loadNotifications()
})
</script>

<style scoped>
.notifications-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
}

.notification-container {
  margin-bottom: 20px;
}

.notification-filter {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.read-status {
  color: #909399;
  font-size: 14px;
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>